package com.hm.search.interceptor;
import com.hm.search.utils.UserHolder;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头
        String authorization = request.getHeader("authorization");
        if (StringUtils.isBlank(authorization)) {

            //没有用户信息,未登录
            throw new RuntimeException("用户未登录");
            //或者 return false; response.setStatus(403);
        }
        //2.转换用户id
        Long userId = Long.valueOf(authorization);
        //3.存入ThreadLocal
        UserHolder.setUser(userId);
        //4.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //用完清理掉
        UserHolder.removeUser();
    }
}
